package com.ggb.reactive.utils

import io.jsonwebtoken.Claims
import io.jsonwebtoken.Jwts
import io.jsonwebtoken.SignatureAlgorithm
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Component
import java.nio.charset.StandardCharsets


@Component
class JwtUtil {
    //@Value("\${app.jwt.admin-secret-key}") // 从配置文件获取密钥
    //private val secretKey: String? = null
    fun generateToken(secretKey:String?,username: String?): String {
        return Jwts.builder()
            .setSubject(username)
            .signWith(SignatureAlgorithm.HS512, secretKey?.toByteArray(StandardCharsets.UTF_8))
            .compact()
    }

    fun parseJWT( secretKey:String?,token: String?): Claims? {
        return try {
            // 得到DefaultJwtParser
            val claims = Jwts.parser() // 设置签名的秘钥
                .setSigningKey(secretKey!!.toByteArray(StandardCharsets.UTF_8)) // 设置需要解析的jwt
                .parseClaimsJws(token).body
            claims
        } catch (e: Exception) {
            null
        }
    }

    fun validateToken(secretKey:String?,token: String?): Boolean {
        return try {
            // 得到DefaultJwtParser
            val claims = Jwts.parser() // 设置签名的秘钥
                .setSigningKey(secretKey!!.toByteArray(StandardCharsets.UTF_8)) // 设置需要解析的jwt
                .parseClaimsJws(token).body
            claims.get("userId", Long::class.java) != null
        } catch (e: Exception) {
            false
        }
    }
}